#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>

// 子进程写
void ChildWrite(int wfd)
{
    char buffer[1024];
    int cnt = 0;
    while (1)
    {
        snprintf(buffer, sizeof(buffer), "我是子进程, 我的pid是: %d, cnt: %d ", getpid(), cnt++);
        // 写入生成的字符 (勿将用sizeof写入1024个字符)
        write(wfd, buffer, strlen(buffer));
        sleep(1);
    }
}

// 父进程读
void ParentRead(int rfd)
{
    char buffer[1024];
    while (1)
    {
        buffer[0] = 0;
        ssize_t len = read(rfd, buffer, sizeof(buffer) - 1);
        if (len > 0)
        {
            buffer[len] = 0;
            std::cout << "子进程说: " << buffer << std::endl;
        }
    }
}

int main()
{
    // 为读写端分配文件描述符

    int pipefd[2];
    int ret = pipe(pipefd);
    if (ret < 0)
    {
        std::cerr << "Error creating pipe" << std::endl;
        std::exit(1);
    }

    // 创建子进程
    pid_t id = fork();
    if (id == 0)
    {
        // child
        // 创建连接信道 p-> r child-> w
        close(pipefd[0]);
        // 子进程写入
        ChildWrite(pipefd[1]);
        exit(0);
    }

    close(pipefd[1]);
    // 父进程读入
    ParentRead(pipefd[0]);
    waitpid(id, nullptr, 0);
}